<template>
  <base-table-layout
    title="物资入库管理"
    :total="total"
    :current-page="currentPage" 
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <div class="search-form">
        <div class="search-form__row">
          <el-select
            v-model="searchForm.materialId"
            placeholder="选择物资"
            clearable
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleSearch"
            @visible-change="handleVisibleChange"
          >
            <el-option 
              v-for="item in materialList"
              :key="item.materialId"
              :label="item.materialName"
              :value="item.materialId"
            />
          </el-select>
          <el-select
            v-model="searchForm.deptId"
            placeholder="选择仓库"
            clearable
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleSearch"
          >
            <el-option 
              v-for="item in warehouseList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            />
          </el-select>
          <el-select
            v-model="searchForm.receiptType"
            placeholder="入库类型"
            clearable
            style="width: 200px;"
            class="filter-item"
          >
            <el-option label="采购" :value="1" />
            <el-option label="调拨" :value="3" />
            <el-option label="生产" :value="2" />
          </el-select>
          <div class="search-form__btns">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
            >搜索</el-button>
            <el-button
              type="info"
              icon="el-icon-refresh"
              @click="resetSearch"
            >重置</el-button>
          </div>
        </div>
      </div>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >入库</el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >批量删除</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="56"
        />
        <el-table-column prop="receiptId" label="入库ID"/>
        <el-table-column label="物资名称" width="200">
          <template slot-scope="scope">
            {{ getMaterialName(scope.row.materialId) }}
          </template>
        </el-table-column>
        <el-table-column label="仓库名称" width="200">
          <template slot-scope="scope">
            {{ getWarehouseName(scope.row.deptId) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="入库数量" width="100" align="right" />
        <el-table-column prop="receiptType" label="入库类型" width="100">
          <template slot-scope="scope">
            <el-tag
              :type="getReceiptTypeTagType(scope.row.receiptType)"
              size="medium"
            >
              {{ getReceiptTypeLabel(scope.row.receiptType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="receiptTime" label="入库时间" width="180" />
        <el-table-column prop="operator" label="操作人" width="100" />
        <el-table-column prop="remark" label="备注" min-width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="!scope.row.remark">-</span>
            <span v-else-if="scope.row.remark.length <= 20">{{ scope.row.remark }}</span>
            <el-button v-else type="text" @click="showRemarkDialog(scope.row.remark)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑入库对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
        <el-form :model="receiptForm" :rules="rules" ref="receiptForm" label-width="100px">
          <div class="form-row">
            <el-form-item label="物资名称" prop="materialId">
              <el-select
                v-model="receiptForm.materialId"
                placeholder="选择物资"
                clearable
                style="width: 100%"
                @change="handleMaterialChange"
                :disabled="dialogTitle === '编辑入库记录'"
              >
                <el-option
                  v-for="item in materialList"
                  :key="item.materialId"
                  :label="item.materialName"
                  :value="item.materialId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="仓库" prop="deptId">
              <el-select
                v-model="receiptForm.deptId"
                placeholder="选择仓库"
                clearable
                style="width: 100%"
                @change="handleDepartmentChange"
                :disabled="dialogTitle === '编辑入库记录'"
              >
                <el-option 
                  v-for="item in warehouseList"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="form-row">
            <el-form-item label="入库数量" prop="quantity">
              <el-input-number 
                v-model="receiptForm.quantity" 
                :min="1" 
                style="width: 100%"
                :disabled="dialogTitle === '编辑入库记录'"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="入库类型" prop="receiptType">
              <el-select v-model="receiptForm.receiptType" placeholder="请选择入库类型" style="width: 100%">
                <el-option label="采购" :value="1" />
                <el-option label="生产" :value="2" />
                <el-option label="调拨" :value="3" />
              </el-select>
            </el-form-item>
          </div>
          <div class="form-row">
            <el-form-item label="入库时间" prop="receiptTime">
              <el-date-picker
                v-model="receiptForm.receiptTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="操作人" prop="operator">
              <el-input v-model="receiptForm.operator"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="receiptForm.remark" rows="3" maxlength="500" show-word-limit></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 备注详情弹窗 -->
      <el-dialog
        title="备注详情"
        :visible.sync="remarkDialogVisible"
        width="30%"
      >
        <span style="word-break: break-all;">{{ currentRemark }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="remarkDialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'MaterialReceiptView',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      materialList: [], // 物资列表
      warehouseList: [], // 仓库列表
      searchForm: {
        materialId: undefined,
        deptId: undefined,
        receiptType: undefined,
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      selectedRows: [], // 新增选中行数据
      receiptForm: {
        materialId: undefined,
        deptId: undefined,
        quantity: 1,
        receiptType: 1,
        receiptTime: '',
        operator: '',
        remark: ''
      },
      rules: {
        materialId: [
          { required: true, message: '请选择物资', trigger: 'change' }
        ],
        deptId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入入库数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
        ],
        receiptType: [
          { required: true, message: '请选择入库类型', trigger: 'change' }
        ],
        receiptTime: [
          { required: true, message: '请选择入库时间', trigger: 'change' }
        ],
        operator: [
          { required: true, message: '请输入操作人', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
        ]
      },
      remarkDialogVisible: false,
      currentRemark: ''
    }
  },
  methods: {
    getReceiptTypeLabel(type) {
      const types = {
        1: '采购',
        2: '生产',
        3: '调拨'
      }
      return types[type] || '未知'
    },
    
    getReceiptTypeTagType(type) {
      const types = {
        1: 'success',  // 绿色
        2: 'warning',  // 黄色
        3: 'primary'   // 蓝色
      }
      return types[type] || 'info'
    },
    
    async handleLoadData() {
      try {
        this.loading = true
        const response = await request.get('/material/receipt/page', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            ...this.searchForm
          }
        })
        
        this.tableData = response.records
        this.total = response.total
      } catch (error) {
        console.error('获取入库数据失败:', error)
        this.$message.error('获取入库数据失败')
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    handleSearch: _.debounce(async function () {
      this.currentPage = 1
      await this.handleLoadData()
    }, 300),

    resetSearch() {
      this.searchForm = {
        materialId: undefined,
        deptId: undefined,
        receiptType: undefined,
      }
      this.currentPage = 1
      this.handleLoadData()
    },


    handleAdd() {
      this.dialogTitle = '新增入库记录'
      this.receiptForm = {
        materialId: undefined,
        deptId: undefined,
        quantity: 1,
        receiptType: 1,
        receiptTime: undefined,
        operator: '',
        remark: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = '编辑入库记录'
      this.receiptForm = { 
        ...row,
        materialId: Number(row.materialId),
        deptId: Number(row.deptId),
        quantity: Number(row.quantity),
        receiptType: Number(row.receiptType),
        receiptTime: row.receiptTime,
        operator: row.operator,
        remark: row.remark
      }
      this.dialogVisible = true
    },

    handleMaterialChange(value) {
      this.receiptForm.materialId = Number(value)
    },

    handleDepartmentChange(value) {
      this.receiptForm.deptId = Number(value)
    },

    async handleDelete({ receiptId }) {
      try {
        await this.$confirm('确认删除该入库记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const res = await request.delete(`/material/receipt/${receiptId}`)
        if (res) {  // 由于request.js已经处理了data，所以直接判断返回值
          this.$message.success('删除成功')
          await this.handleLoadData()
        } else {
          this.$message.error('删除失败')
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    // 新增选择行的方法
    handleSelectionChange(val) {
      this.selectedRows = val
    },

    // 批量删除的方法
    async handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的入库记录')
        return
      }

      try {
        await this.$confirm('确认删除选中的入库记录吗？', '提示', {
          type: 'warning'
        })

        const receiptIds = this.selectedRows.map(row => row.receiptId)
        const response = await request.delete('/material/receipt/batch', {
          data: receiptIds  // axios的delete请求需要使用data字段传递请求体
        })

        if (response) {  // 由于request.js已经处理了data，所以直接判断返回值
          this.$message.success('批量删除成功')
          await this.handleLoadData()
        } else {
          throw new Error('批量删除失败')
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },

    async handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      await this.handleLoadData()
    },

    async handleCurrentChange(val) {
      this.currentPage = val
      await this.handleLoadData()
    },

    async submitForm() {
      try {
        const valid = await this.$refs.receiptForm.validate()
        if (!valid) return

        const formData = { ...this.receiptForm }
        let res

        if (formData.receiptId) {
          // 编辑
          res = await request.put('/material/receipt', formData)
        } else {
          res = await request.post('/material/receipt', formData)
        }

        if (res) {  // 由于request.js已经处理了data，所以直接判断返回值
          this.$message.success(formData.receiptId ? '更新成功' : '添加成功')
          this.dialogVisible = false
          await this.handleLoadData()
        } else {
          this.$message.error('保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败，请稍后重试')
      }
    },

    showRemarkDialog(remark) {
      this.currentRemark = remark
      this.remarkDialogVisible = true
    },

    // 获取所有物资列表
    async fetchMaterialList() {
      try {
        const response = await request.get('/material/materialAll')
        console.log('物资列表响应:', response) // 添加日志查看响应数据
        if (Array.isArray(response)) {
          this.materialList = response.map(item => ({
            materialId: item.materialId,
            materialName: item.materialName || '未知物资'
          }))
        } else {
          this.$message.warning('获取物资列表格式异常')
          this.materialList = []
        }
      } catch (error) {
        console.error('获取物资列表失败:', error)
        this.$message.error('获取物资列表失败')
        this.materialList = []
      }
    },

    // 获取仓库列表数据
    async fetchWarehouseList() {
      try {
        const response = await request.get('/departments/page', {
          params: {
            current: 1,
            size: 100,
            deptType: 5  // 仓库类型
          }
        })
        if (response && response.records) {
          this.warehouseList = response.records.map(item => ({
            deptId: item.deptId,
            deptName: item.deptName
          }))
        } else {
          this.$message.warning('获取仓库列表失败')
          this.warehouseList = []
        }
      } catch (error) {
        console.error('获取仓库列表失败:', error)
        this.$message.error('获取仓库列表失败')
        this.warehouseList = []
      }
    },

    // 根据仓库ID获取仓库名称
    getWarehouseName(deptId) {
      if (!deptId || !this.warehouseList || this.warehouseList.length === 0) {
        return '未知仓库'
      }
      const warehouse = this.warehouseList.find(item => Number(item.deptId) === Number(deptId))
      return warehouse ? warehouse.deptName : '未知仓库'
    },

    // 根据物资ID获取物资名称
    getMaterialName(materialId) {
      if (!materialId || !this.materialList || this.materialList.length === 0) {
        return '未知物资'
      }
      const material = this.materialList.find(item => Number(item.materialId) === Number(materialId))
      return material ? material.materialName : '未知物资'
    },

    // 添加下拉框显示状态变化处理方法
    handleVisibleChange(visible) {
      if (!visible) {
        // 当下拉框关闭时，强制更新组件
        this.$forceUpdate()
      }
    }
  },
  created() {
    this.fetchMaterialList()
    this.fetchWarehouseList()
    this.handleLoadData()
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.search-bar {
  margin-bottom: 20px;
}

.search-form {
  &__row {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .filter-item {
      margin-right: 16px;
      
      &:last-child {
        margin-right: 0;
      }
    }
  }
  
  &__btns {
    margin-left: auto;
  }
}

.form-row {
  display: flex;
  gap: 20px;
  
  .el-form-item {
    flex: 1;
    margin-bottom: 18px;
  }
}

// Fix quantity input border styling
:deep(.el-form-item.prop-quantity .el-input-number) {
  .el-input__inner {
    border-radius: 4px;
    border: 1px solid #DCDFE6 !important;
    
    &:hover {
      border-color: #C0C4CC !important;
    }
    
    &:focus {
      border-color: #409EFF !important;
    }
  }
  
  &.is-disabled {
    .el-input__inner {
      background-color: #F5F7FA;
      border-color: #E4E7ED !important;
      color: #C0C4CC;
    }
  }
}
</style>
